package com.sq.universe.system.controller;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sq.universe.base.conf.NonStaticResourceHttpRequestHandler;
import com.sq.universe.base.controller.BaseController;
import com.sq.universe.base.entity.RespEntity;
import com.sq.universe.system.entity.MsgEntity;
import com.sq.universe.system.service.MsgService;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/msg")
@CrossOrigin
@Api(description = "消息管理")
@Slf4j
public class MsgController extends BaseController {

    @Autowired
    private MsgService msgService;

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    /**
     * 查询数据
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/query")
    @RequiresPermissions("system:msg:query")
    public RespEntity query(@RequestBody(required = false) MsgEntity msgEntity) {
        try {
            return new RespEntity("查询成功", msgService.query(msgEntity));
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("查询失败");
        }
    }

    /**
     * 分页查询
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/queryByPage")
    @RequiresPermissions("system:msg:queryByPage")
    public RespEntity queryByPage(@RequestBody(required = false) MsgEntity msgEntity) {
        try {

            PageHelper.startPage(msgEntity.getPageNo(), msgEntity.getPageSize());
            List<MsgEntity> msgList = msgService.query(msgEntity);
            PageInfo<MsgEntity> pageInfo = new PageInfo<MsgEntity>(msgList);
            return new RespEntity("查询成功", pageInfo);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("查询失败");
        }
    }

    /**
     * 分页查询
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/queryByUser")
//    @RequiresPermissions("system:msg:queryByUser")
    public RespEntity queryByUser(@RequestBody(required = false) MsgEntity msgEntity) {
        try {
            log.isTraceEnabled();
            log.error("msgQueryTest");
            PageHelper.startPage(msgEntity.getPageNo(), msgEntity.getPageSize());
            List<MsgEntity> msgList = msgService.queryByUser(msgEntity);
            PageInfo<MsgEntity> pageInfo = new PageInfo<MsgEntity>(msgList);
            return new RespEntity("查询成功", pageInfo);
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("查询失败");
        }
    }

    /**
     * 插入
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/insert")
    @RequiresPermissions("system:msg:insert")
    public RespEntity insert(@RequestBody(required = false) MsgEntity msgEntity) {
        try {
            msgEntity.setMsgCreateTime(new Date());
            msgEntity.setMsgCreateUser(this.getCurrentUser().getUserId());
            msgService.insert(msgEntity);
            return new RespEntity("保存成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("保存失败");
        }
    }

    /**
     * 更新
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/update")
    @RequiresPermissions("system:msg:update")
    public RespEntity update(@RequestBody(required = false) MsgEntity msgEntity) {
        try {
            msgEntity.setMsgUpdateTime(new Date());
            msgEntity.setMsgUpdateUser(this.getCurrentUser().getUserId());
            msgService.update(msgEntity);
            return new RespEntity("更新成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("更新失败");
        }
    }

    /**
     * 删除成功
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/delete")
    @RequiresPermissions("system:msg:delete")
    public RespEntity delete(@RequestBody(required = false) MsgEntity msgEntity) {
        try {
            if (msgEntity.getMsgId() == null) {
                return new RespEntity("删除失败");
            }
            msgEntity.setMsgUpdateTime(new Date());
            msgEntity.setMsgUpdateUser(this.getCurrentUser().getUserId());
            msgService.logicalDelete(msgEntity);
            return new RespEntity("删除成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("删除失败");
        }
    }

    /**
     * 根据ID查询
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/getById")
    @RequiresPermissions("system:msg:getById")
    public RespEntity getById(@RequestBody(required = false) MsgEntity msgEntity) {
        try {
            if (msgEntity.getMsgId() == null) {
                return new RespEntity("请输入id查询");
            }
            return new RespEntity("查询成功", msgService.getById(msgEntity.getMsgId()));
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("查询失败");
        }
    }

    /**
     * 根据实体查询
     *
     * @param msgEntity
     * @return
     */
    @PostMapping("/get")
    @RequiresPermissions("system:msg:get")
    public RespEntity get(@RequestBody(required = false) MsgEntity msgEntity) {
        try {
            return new RespEntity("查询成功", msgService.get(msgEntity));
        } catch (Exception exception) {
            exception.printStackTrace();
            return new RespEntity("查询失败");
        }
    }



    /**
     * 读取文件
     * @param videoName
     * @param response
     */
    @RequestMapping("/getAudioInfo/{videoName}")
    public void getAudioInfo(@PathVariable("videoName")String videoName, HttpServletResponse response, HttpServletRequest request){
        try {
            File file = ResourceUtils.getFile("classpath:static/audio/" + videoName);
            // 获取文件名
//            String filename = file.getName();
            // 清空response
            response.reset();
//            // 设置response的Header
//            response.setCharacterEncoding("UTF-8");
//            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
//            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
//            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
//            response.addHeader("Content-Length", "" + file.length());
//            OutputStream outputStream = new BufferedOutputStream(response.-+());
            Path filePath = Paths.get(file.getAbsolutePath() );
            response.setContentType(Files.probeContentType(filePath));
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);

//            outputStream.write(FileUtil.readBytes(file));
//            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}